package com.example.e03;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class ContentProviderActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_READ_CONTACTS = 1;
    private TableLayout tableLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_provider);

        tableLayout = findViewById(R.id.table_layout);
        Button showAllButton = findViewById(R.id.show_all_contacts);
        Button queryButton = findViewById(R.id.query_contact);
        Button addButton = findViewById(R.id.add_contact);
        Button modifyButton = findViewById(R.id.modify_contact);
        Button deleteButton = findViewById(R.id.delete_contact);

        showAllButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(ContentProviderActivity.this,
                        Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ContentProviderActivity.this,
                            new String[]{Manifest.permission.READ_CONTACTS},
                            PERMISSION_REQUEST_READ_CONTACTS);
                } else {
                    showAllContacts();
                }
            }
        });

        queryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 可实现查询逻辑
            }
        });

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addContact("新联系人", "123456789");
            }
        });

        modifyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 可实现修改逻辑
            }
        });

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 可实现删除逻辑
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showAllContacts();
            } else {
                Toast.makeText(this, "未授予读取联系人权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showAllContacts() {
        tableLayout.removeAllViewsInLayout();
        TableRow headerRow = new TableRow(this);
        String[] headers = {"id", "姓名", "电话"};
        for (String header : headers) {
            TextView textView = new TextView(this);
            textView.setText(header);
            textView.setPadding(5, 5, 5, 5);
            headerRow.addView(textView);
        }
        tableLayout.addView(headerRow);

        ContentResolver resolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = {
                ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
        };
        Cursor cursor = resolver.query(uri, projection, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int idColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
                int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                int phoneColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

                String id = (idColumnIndex != -1) ? cursor.getString(idColumnIndex) : "";
                String name = (nameColumnIndex != -1) ? cursor.getString(nameColumnIndex) : "未知";
                String phone = (phoneColumnIndex != -1) ? cursor.getString(phoneColumnIndex) : "未知";


                TableRow row = new TableRow(this);
                TextView idView = new TextView(this);
                idView.setText(id);
                idView.setPadding(5, 5, 5, 5);
                row.addView(idView);

                TextView nameView = new TextView(this);
                nameView.setText(name);
                nameView.setPadding(5, 5, 5, 5);
                row.addView(nameView);

                TextView phoneView = new TextView(this);
                phoneView.setText(phone);
                phoneView.setPadding(5, 5, 5, 5);
                row.addView(phoneView);

                tableLayout.addView(row);
            }
            cursor.close();
        }
    }

    private void addContact(String name, String phone) {
        ContentValues values = new ContentValues();
        Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        values.clear();
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        values.clear();
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        Toast.makeText(this, "联系人添加成功", Toast.LENGTH_SHORT).show();
    }
}    